package com.magenta.maxoptra.geocoding.geoinformsputnik;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: Zlygostev
 * Date: 24.04.12
 * Time: 15:28
 */
public class Settings {
    private static final Pattern PATTERN = Pattern.compile("<SearchLayer>(.+?)</SearchLayer>");

    private String searchLayer;
    private List<Integer> scales;

    public Settings(String settingsUrl) {
        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            docFactory.setNamespaceAware(false);
            DocumentBuilder builder;
            builder = docFactory.newDocumentBuilder();
            Document doc = builder.parse(InfoProvider.getGeoSamaraResourceUrl(settingsUrl + ".xml").toURI().toString());
            XPathFactory factory = XPathFactory.newInstance();

            XPathExpression expr = factory.newXPath().compile("/settings/instruments/instrument[className='TextRequest']/parameters");
            NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            if (nodes.getLength() > 0) {
                final Matcher matcher = PATTERN.matcher(nodes.item(0).getTextContent());
                if (matcher.find()) {
                    searchLayer = matcher.group(1);
                }
            }

            scales = new ArrayList<Integer>();
            expr = factory.newXPath().compile("/settings/scales/scale");
            nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            if (nodes.getLength() > 0) {
                for (int s = 0; s < nodes.getLength(); s++) {
                    scales.add(Integer.valueOf(nodes.item(s).getTextContent()));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String getSearchLayer() {
        return searchLayer;
    }

    public List<Integer> getScales() {
        return scales;
    }
}